package priv.lhy.ecm.config.DatabaseConfig;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import priv.lhy.ecm.config.DisposeProperties;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @author: lihy
 * date: 2019/9/16 11:42
 * description:
 */
@Configuration
@MapperScan({"priv.lhy.ecm.mapper"})
@ConditionalOnClass(name="com.mysql.jdbc.Driver")
public class SessionFactoryConfiguration {

    // mybatis mapper文件所在路径
    //@Value("${mapper_path}")
    private String mapperPath = "mappers/*Mapper.xml";

    // 实体类所在的package
    //@Value("${entity_package}")
    private String entityPackage = "priv.lhy.ecm.dal";

    private DataSource dataSource;

    public SessionFactoryConfiguration(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Bean
    public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 扫描mybatis配置文件
        //sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
        // 扫描相关mapper文件
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath;
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
        // 调用dataSource
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 映射实体类
        sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
        return sqlSessionFactoryBean;
    }
}
